# routers/efence.py
from fastapi import APIRouter, Depends, HTTPException, Request, Form,Cookie
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from sqlalchemy.orm import Session
from database import get_db
from models import Area, ElectFence
from datetime import datetime
import paho.mqtt.client as mqtt
import json
from core.logger import app_logger as logger
from utils import get_mqtt_client
from urllib.parse import unquote 
from datetime import datetime
from typing import Optional
from utils import validate_session

router = APIRouter()
templates = Jinja2Templates(directory="templates")
templates.env.filters["urldecode"] = unquote
 
# 初始化MQTT客户端
mqtt_client = None

def init_mqtt():
    global mqtt_client
    if mqtt_client is None:
        mqtt_client = get_mqtt_client()
        
        def on_connect(client, userdata, flags, rc):
            if rc == 0:
                logger.info("电子围栏MQTT客户端成功连接")
                client.subscribe("efence/status")
                logger.info("电子围栏订阅状态主题成功")
            else:
                logger.info(f"MQTT连接失败，错误码: {rc}")
        
        def on_message(client, userdata, msg):
            try:
                topic = msg.topic
                payload = msg.payload.decode('utf-8')
                logger.info(f"收到MQTT消息: {topic} - {payload}")
                
                if topic == "efence/status":
                    data = json.loads(payload)
                    device_id = data.get("id")
                    cmd = data.get("cmd")
                    
                    if device_id and cmd:
                        db: Session = next(get_db())
                        try:
                            # 检查设备是否存在（不包括已删除的）
                            fence = db.query(ElectFence).filter(
                                ElectFence.FenceName == device_id,
                                ElectFence.DeadTime == None
                            ).first()
                            current_time = datetime.now()
                            
                            if fence:
                                # 更新现有设备
                                fence.FenceState = cmd
                                fence.UpdateTime = current_time
                                logger.info(f"更新电子围栏设备: {device_id} 状态为: {cmd}")
                            else:
                                # 创建新设备
                                fence = ElectFence(
                                    FenceName=device_id,
                                    FenceState=cmd,
                                    FenceDesc=f"电子围栏设备 {device_id}",
                                    CreateTime=current_time,
                                    UpdateTime=current_time
                                )
                                db.add(fence)
                                logger.info(f"创建新电子围栏设备: {device_id}")
                            
                            db.commit()
                        except Exception as e:
                            db.rollback()
                            logger.error(f"处理电子围栏状态更新失败: {str(e)}")
                        finally:
                            db.close()
                    else:
                        logger.warning("无效的电子围栏状态消息格式")
            except Exception as e:
                logger.error(f"处理MQTT消息异常: {str(e)}")
        
        mqtt_client.on_connect = on_connect
        mqtt_client.on_message = on_message
        mqtt_client.loop_start()

# 应用启动时初始化MQTT
@router.on_event("startup")
async def startup_event():
    init_mqtt()

@router.get("/fence/devices")
async def fence_devices(request: Request, 
                        SessionId: Optional[str] = Cookie(None),
                        UserName: Optional[str] = Cookie(None),
                        db: Session = Depends(get_db)):
    if not SessionId or not UserName or not validate_session(SessionId, UserName):
        return RedirectResponse(url="/")
    
    # 查询所有区域
    areas = db.query(Area).all()

    # 查询所有未删除的电子围栏设备
    # fences = db.query(ElectFence).filter(ElectFence.DeadTime == None).all()
    fences = db.query(
        ElectFence,
        Area.AreaName
    ).outerjoin(
        Area, ElectFence.AreaId == Area.AreaId
    ).filter(
        ElectFence.DeadTime == None
    ).all()

    fence_data = []
    for fence, area_name in fences:
        fence_dict = fence.to_dict()
        fence_dict["AreaName"] = area_name
        fence_data.append(fence_dict)

    return templates.TemplateResponse("ef_devices.html", {
        "request": request,
        "fences": fence_data,
        "areas": areas  # 传递区域列表
    })  

@router.get("/api/fence/devices")
async def get_fence_devices(db: Session = Depends(get_db)):
    # 修改查询，包含区域名称
    fences = db.query(
        ElectFence,
        Area.AreaName
    ).outerjoin(
        Area, ElectFence.AreaId == Area.AreaId
    ).filter(
        ElectFence.DeadTime == None
    ).all()
    
    # 重构数据格式
    fence_data = []
    for fence, area_name in fences:
        fence_dict = fence.to_dict()
        fence_dict["AreaName"] = area_name
        fence_data.append(fence_dict)
    
    return {"status": "success", "fences": fence_data}

@router.post("/api/fence/update")
async def update_fence_device(
    fence_id: int = Form(...),
    fence_desc: str = Form(...),
    db: Session = Depends(get_db)
):
    try:
        fence = db.query(ElectFence).filter(
            ElectFence.FenceId == fence_id,
            ElectFence.DeadTime == None
        ).first()
        if not fence:
            raise HTTPException(status_code=404, detail="设备未找到")
        
        fence.FenceDesc = fence_desc
        fence.UpdateTime = datetime.now()
        db.commit()
        
        return {"status": "success", "message": "设备信息已更新"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新失败: {str(e)}")

# 添加区域更新接口
@router.post("/api/fence/update-area")
async def update_fence_area(
    fence_id: int = Form(...),
    area_id: int = Form(...),
    db: Session = Depends(get_db)
):
    try:
        fence = db.query(ElectFence).filter(
            ElectFence.FenceId == fence_id,
            ElectFence.DeadTime == None
        ).first()
        
        if not fence:
            raise HTTPException(status_code=404, detail="设备未找到")
        
        # 检查区域是否存在
        area = db.query(Area).filter(Area.AreaId == area_id).first()
        if not area:
            raise HTTPException(status_code=400, detail="区域不存在")
        
        fence.AreaId = area_id
        fence.UpdateTime = datetime.now()
        db.commit()
        
        return {"status": "success", "message": "区域已更新"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新失败: {str(e)}")


@router.delete("/api/fence/delete")
async def delete_fence_device(
    fence_id: int,
    db: Session = Depends(get_db)
):
    try:
        fence = db.query(ElectFence).filter(
            ElectFence.FenceId == fence_id,
            ElectFence.DeadTime == None
        ).first()
        if not fence:
            raise HTTPException(status_code=404, detail="设备未找到")
        
        # 逻辑删除：设置DeadTime为当前时间
        fence.DeadTime = datetime.now()
        db.commit()
        
        return {"status": "success", "message": "设备已删除"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除失败: {str(e)}")